package com.zzusedating.androidapp.tools;

import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class BasicCallback implements Callback {
    private static final String TAG = "BasicCallback";
    private Handler handler;
    private int code;
    private int status;

    protected BasicCallback(Handler h){
        handler = h;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if (handler != null)
            handler.sendMessage(ConstantsTools.createMessage());
    }
    @Override
    abstract public void onResponse(Call call, @NonNull Response response);

    protected Object getObject(@NonNull Response response){
        if (response.code() != 200){
            try {
                Log.e(TAG, "checkResponse: code: " + response.code() + " with " + response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(response.body().string());
            status = jsonObject.getInt("status");
            if (status == 1)
                return jsonObject.get("data");
            code = jsonObject.getInt("code");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected int getStatus(Response response){
        if (response.code() != 200){
            Log.e(TAG, "checkResponse: code: " + response.code());
            return ConstantsTools.NETWORK_ERROR_I;
        }
        try {
            JSONObject jsonObject = new JSONObject(response.body().string());
            code = jsonObject.getInt("code");
            return status = jsonObject.getInt("status");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }
    public int getCode() {
        return code;
    }

    public Handler getHandler() {
        return handler;
    }
}
